package javabase.exception.closeres;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Wolf implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
	
	public Wolf(String name) {
		super();
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Wolf other = (Wolf) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

public class CloseResource {
	public CloseResource() {

	}
	
	public static void main(String[] args) {
		Wolf wolf = new Wolf("大灰狼");
		Wolf wolf1 = null;
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			// 创建对象输出流
			oos = new ObjectOutputStream(new FileOutputStream("a.bin"));
			// 创建对象输入流
			ois = new ObjectInputStream(new FileInputStream("a.bin"));
			// 序列化输出java对象
			oos.writeObject(wolf);
			oos.flush();
			// 反序列化恢复java对象
			wolf1 = (Wolf) ois.readObject();
			System.out.println(wolf1);
		} catch (Exception e) {
			
		} finally {
			// 使用finally关闭资源
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

}
